package thread2;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTimer {
    static class Task implements Comparable<Task> {
        //要执行的任务是什么
        private Runnable runnable;
        //什么时间去执行
        private long time;

        public Task(Runnable runnable, long after) {
            this.runnable = runnable;
            this.time = System.currentTimeMillis() + after;
        }

        public void run() {
            runnable.run();
        }


        @Override
        public int compareTo(Task o) {
            return (int) (this.time - o.time);
        }
    }

    private PriorityBlockingQueue<Task> tasks = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable, long after) {
        Task task = new Task(runnable, after);
        tasks.put(task);
    }

    private Object object = new Object();

    //扫描线程
    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Task task = tasks.take();
                    long curTime = System.currentTimeMillis();
                    if (curTime < task.time) {
                        tasks.put(task);
                        synchronized (object) {
                            object.wait(task.time - curTime);
                        }
                    } else {
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }
}

public class Test4 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        }, 3000);

        System.out.println("hello main");
    }
}
